package com.luke.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Descrtption BioServer
 * @Author luke
 * @Date 2020/4/22
 **/
public class BioServer {

    public static void main(String[] args){
        int port = 8762;
        ServerSocket serverSocket = null;
        ExecutorService executorService = null;
        try {
            serverSocket = new ServerSocket(port);
            executorService = Executors.newCachedThreadPool(); //线程池
            while(true){
                System.out.println("【等待客户端连接】");
                Socket socket = serverSocket.accept(); //阻塞在等待客户端连接
                System.out.println("【接收到客户端连接】");
                executorService.execute(new SocketHandler(socket));//交给子线程处理
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(serverSocket != null){
                try {
                    System.out.println("BioServer close");
                    serverSocket.close();
                    executorService.shutdown();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Socket 处理器
     */
    static class SocketHandler implements Runnable{

        private Socket socket;

        public SocketHandler(Socket socket){
            this.socket = socket;
        }

        public void run() {
            InputStream inputStream = null;
            BufferedReader bufferedReader = null;
            try {
                inputStream = socket.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                while(true){
                    System.out.println("等待客户端发送数据《《");
                    String readLine = bufferedReader.readLine(); //阻塞在输入流
                    System.out.println("获取到客户端数据《《");
                    if(readLine == null)
                        break;
                    System.out.println("接收到数据："+ readLine);
                }
            } catch (IOException e) {
                System.out.println("客户端断开连接");
            }finally {
                if(inputStream != null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(bufferedReader != null){
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
